package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itheima.utils.HttpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;



@Controller
@RequestMapping("/weChat")
public class WeChatController {

    @RequestMapping("/login")
    public String login(){
        //第一步：用户同意授权，获取code
        String appId = "wx6d78dc76a98bef3f";
        String redirectUrl = "https://x3npaec.nat.ipyingshe.com/weChat/userInfo.do";

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return "redirect:" + url;
    }

    @RequestMapping(value="/userInfo", produces="text/html;charset=UTF-8")
 /*   @ResponseBody*/
    public String userInfo(String code,String state){
        //第二步：通过code换取网页授权access_token
        String appId = "wx6d78dc76a98bef3f";
        String appSecret = "d11eb5d70b92ef20d8abe0112e6e5e10";
        //获取code后，请求以下链接获取access_token： https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        //发送请求 get 服务端发送了一个get请求 到微信的服务端
        String accessTokenJson = HttpUtils.doGet(requestUrl);
        //json解析
        System.out.println(accessTokenJson);
        //map解析
        Map<String,Object> map = JSON.parseObject(accessTokenJson,new TypeReference<Map<String,Object>>(){}.getType());
        //取出所需求的参数
        String accessToken = String.valueOf(map.get("access_token"));
        String openId = String.valueOf(map.get("openid"));
        //获取用户信息 拉取用户信息(需scope为 snsapi_userinfo)
        //http：GET（请使用https协议） https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        String response = HttpUtils.doGet(userInfoUrl);
        //拿到返回值  unionid  联合ID  opendID 网页登录 对我们来说他是一个，app微信登录 openId 又是另一个
        // openId 去user表查询，如果有 就是登录成功，如果没有 注册并登录成功，同时把登录信息当到session中
        System.out.println(response);
        return "/pages/index.html";
    }

}
